package com.baomidou.springwind.controller.city;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.entity.*;
import com.baomidou.springwind.enums.NodeTypeEnum;
import com.baomidou.springwind.pojo.*;
import com.baomidou.springwind.service.WorkTimeService;
import com.baomidou.springwind.service.ProjectService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 城市配送:客户分析
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/city")
public class WorkTimeController extends BaseController {

    @Autowired
    private WorkTimeService workTimeService;
    @Autowired
    private ProjectService projectService;
    /**
     * 客户分析主界面
     */
    @RequestMapping("/work")
    @Permission("1001")
    public String customGroup(Model model) {
        return pjaxPath("/lpp/network/city/work/main", model);

    }
    /**
     * 城市数据导入--
     */
    @RequestMapping("/work/list")
    @Permission("1001")
    public String customList(Model model) {
        EntityWrapper<Project> wrapper = new EntityWrapper<Project>();
        wrapper.eq("operator_id",getCurrentUserId());
        wrapper.in("state", Arrays.asList("1", "2"));
        model.addAttribute("prjList", projectService.selectList(wrapper));
        return pjaxPath("/file/work_time_list", model);
    }

    /**
     * 城市数据导入--客户分析数据--ajax获取数据
     */
    @ResponseBody
    @RequestMapping("/work/getData")
    @Permission("1001")
    public String getData(Page<WorkTime> page,String batchId) {
        page = new Page<WorkTime>(page.getCurrent(), page.getSize());
        EntityWrapper<WorkTime> wrapper = new EntityWrapper<WorkTime>();
        if (StringUtils.isNotEmpty(batchId)){
            wrapper.eq("batch_id",batchId);
        }
        wrapper.eq("operator_id", getCurrentUserId());
        wrapper.orderBy("create_time", false);
        page = workTimeService.selectPage(page, wrapper);
        JSONObject jo = new JSONObject();
        jo.put("recordsFiltered", page.getTotal());
        jo.put("recordsTotal", page.getTotal());
        ArrayList<WorkTimeColne> arrayList=new ArrayList<WorkTimeColne>();
        for (int i=0;i<page.getRecords().size();i++){
            WorkTimeColne workTimeColne=new WorkTimeColne();
            arrayList.add(workTimeColne);
            long a1=page.getRecords().get(i).getId();
            arrayList.get(i).setId(null);
            arrayList.get(i).setName(page.getRecords().get(i).getName());
            arrayList.get(i).setBatchId(page.getRecords().get(i).getBatchId());
            arrayList.get(i).setBatchName(page.getRecords().get(i).getName());
            arrayList.get(i).setOperatorId(page.getRecords().get(i).getOperatorId());
            arrayList.get(i).setCreateTime(page.getRecords().get(i).getCreateTime());
            JSONArray jsonArray=new JSONArray();
            jsonArray=JSONArray.parseArray(page.getRecords().get(i).getTime());
            int j=0;
                arrayList.get(i).setTime1(jsonArray.get(j).toString());
                arrayList.get(i).setTime2(jsonArray.get(j++).toString());
                arrayList.get(i).setTime3(jsonArray.get(j++).toString());
                arrayList.get(i).setTime4(jsonArray.get(j++).toString());
                arrayList.get(i).setTime5(jsonArray.get(j++).toString());
                arrayList.get(i).setTime6(jsonArray.get(j++).toString());
                arrayList.get(i).setTime7(jsonArray.get(j++).toString());
                arrayList.get(i).setTime8(jsonArray.get(j++).toString());
                arrayList.get(i).setTime9(jsonArray.get(j++).toString());
                arrayList.get(i).setTime10(jsonArray.get(j++).toString());
                arrayList.get(i).setTime11(jsonArray.get(j++).toString());
                arrayList.get(i).setTime12(jsonArray.get(j++).toString());
                arrayList.get(i).setTime13(jsonArray.get(j++).toString());
                arrayList.get(i).setTime14(jsonArray.get(j++).toString());
                arrayList.get(i).setTime15(jsonArray.get(j++).toString());
                arrayList.get(i).setTime16(jsonArray.get(j++).toString());
                arrayList.get(i).setTime17(jsonArray.get(j++).toString());
                arrayList.get(i).setTime18(jsonArray.get(j++).toString());
                arrayList.get(i).setTime19(jsonArray.get(j++).toString());
                arrayList.get(i).setTime20(jsonArray.get(j++).toString());
                arrayList.get(i).setTime21(jsonArray.get(j++).toString());
                arrayList.get(i).setTime22(jsonArray.get(j++).toString());
                arrayList.get(i).setTime23(jsonArray.get(j++).toString());
                arrayList.get(i).setTime24(jsonArray.get(j++).toString());
                arrayList.get(i).setTime25(jsonArray.get(j++).toString());
        }
        if (arrayList.size() > 0) {
            Project project = projectService.selectById(arrayList.get(0).getBatchId());
            for (WorkTimeColne workTimeColne : arrayList) {
                workTimeColne.setBatchName(project == null ? "未找到所属项目" : project.getName());
            }
        }
        jo.put("data", arrayList);
        return toJson(jo);
    }



    /**
     * 客户分析--物料种类划分医院
     */
    @ResponseBody
    @RequestMapping("/work/bar1")
    @Permission("1001")
    public String  customGroupByType() throws Exception{
        EntityWrapper<WorkTime> wrapper = new EntityWrapper<WorkTime>();
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("operator_id", getCurrentUserId());
        final List<WorkTime> workTimes = workTimeService.selectList(wrapper);
        if(workTimes.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONObject ret = new JSONObject();
        //找到t需要的数据
        JSONArray t = new JSONArray();
        for (int i=20;i<24;i++){
            t.add(i+":00");
            t.add(i+":30");
        }
        for(int i=0;i<20;i++){
            t.add(i+":00");
            t.add(i+":30");
        }
        //找到a1需要的数据
        JSONArray a1 = new JSONArray();//回收人员作业人数
        JSONArray a2 = new JSONArray();//配送人员作业人数
        double times=0;
        int temp=0;
        //回收人员加载a1数据
        for(int i=0;i<18;i++){
            for (int j=0;j<workTimes.size();j++){
                JSONArray jsonArray=JSONArray.parseArray(workTimes.get(j).getTime());
                times=times+Integer.valueOf(jsonArray.get(i).toString());
            }
            a1.add(times);
            a2.add(0);
            times=0;
        }
        //配送人员加载a2数据
        for(int i=18;i<48;i++){
            for (int j=0;j<workTimes.size();j++){
                JSONArray jsonArray=JSONArray.parseArray(workTimes.get(j).getTime());
                times=times+Double.valueOf(jsonArray.get(i).toString());
            }
            a1.add(0);
            a2.add(times);
            times=0;
        }

        ret.put("x",t);
        ret.put("s1",a1);
        ret.put("s2",a2);
        return callbackSuccess(ret);

    }
    @ResponseBody
    @Permission("1001")
    @RequestMapping("/work/download")
    public byte[] expend() {
        // String file_name=request.getParameter("file_name"); //要下载的文件名
        String file_name="订单.xls";
        try{
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
             file_name = new String(file_name.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
             file_name = URLEncoder.encode(file_name, "UTF-8");//IE浏览器
        }}catch (Exception e){

        }
        String realpath=request.getSession().getServletContext().getRealPath("/");//获取服务器的物理路径
        String temp1 = File.separator;//路径分隔符("\\")
        String filedownload_url=realpath+"WEB-INF"+temp1+"static"+temp1+"template"+temp1+file_name;//要提供下载的文件的物理路径＋文件名
        System.out.println("filedownload="+filedownload_url);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=\""+file_name+"\"");
        //新建文件输入输出流
        OutputStream output = null;
        FileInputStream fis = null;
        try{
            File f = new File(filedownload_url);//新建File对象
            output = response.getOutputStream();//新建文件输入输出流对象
            fis = new FileInputStream(f);
            byte[] b = new byte[(int)f.length()]; //设置每次写入缓存大小
            //把输出流写入客户端
            int i = 0;
            while((i = fis.read(b)) > 0){
                output.write(b, 0, i);
            }
            output.flush();
            if(fis != null)
            {
                fis.close();
                fis = null;
            }
            if(output != null)
            {
                output.close();
                output = null;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
